package com.chenjiajin.adive;

import com.chenjiajin.domain.PojoDemo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 获取方法的返回值
 *
 * @author chenjiajin
 * @date 2022/8/23
 */
@Slf4j
@ControllerAdvice
public class ApiResponseBody implements ResponseBodyAdvice<PojoDemo> {
    // 原理: https://blog.csdn.net/codeblf2/article/details/102732255
    // 使用@ControllerAdvice，这个注解标注的类需要实现ResponseBodyAdvice，这样在response返回前会调用这个类的beforeBodyWrite方法，我们就在beforeBodyWrite方法里面做文章，来进行“曲线救国”

    public static PojoDemo returnData;


    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        log.info("supports");
        return true;
    }


    @Override
    public PojoDemo beforeBodyWrite(PojoDemo body,
                                    MethodParameter returnType,
                                    MediaType selectedContentType,
                                    Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                    ServerHttpRequest request,
                                    ServerHttpResponse response) {

        returnData = body;
        return null;
    }
}
